<template>
	<view class="album_box">
		<view class="container2">
			<view class="df ac sb">
				<view class="">共计：{{ total }}张</view>
			</view>
			<view class="shebei mt10">
				<view class="f600 f18 mb10">
					设备展示（{{equipment_img.length}}）
				</view>
				
				<view class="img_box df " v-if="page_width">
					<view class="img_sty" v-for="(item,index) in equipment_img" :key="index"
						:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="previewImg('equipment_img',index)">
						<image style="width:100%;height:100%" :src="getImgSrc(item)" mode="aspectFill" />
						<view class="detail_btn" @click.stop="deleteImg('equipment_img',index)">
							<image style="width: 60rpx;"
								:src="getImgSrc('/uploads/20241024/17297417766719c3d068382.png')" mode="widthFix">
							</image>
						</view>
					</view>
					<view class="add_product_item df ac"
						:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="uploadFile('equipment_img')">
						<van-icon name="plus" size="30" color="#CDCDCD" />
						<view class="name f18 f500 mt10">
							上传照片
						</view>
					</view>
				</view>
			</view>
			<view class="shebei mt10">
				<view class="f600 f18 mb10">
					车间展示（{{company_environment.length}}）
				</view>
				<view class="img_box df" v-if="page_width">
					<view class="img_sty" v-for="(item,index) in company_environment" :key="index"
						:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="previewImg('company_environment',index)">
						<image style="width:100%;height: 100%;" :src="getImgSrc(item)" mode="aspectFill" />

						<view class="detail_btn" @click.stop="deleteImg('company_environment',index)">
							<image style="width: 60rpx;"
								:src="getImgSrc('/uploads/20241024/17297417766719c3d068382.png')" mode="widthFix">
							</image>
						</view>
					</view>
					<view class="add_product_item df ac"
						:style="'width:' + comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="uploadFile('company_environment')">
						<van-icon name="plus" size="30" color="#CDCDCD" />
						<view class="name f18 f500 mt10">
							上传照片
						</view>
					</view>
				</view>
			</view>
			<view class="shebei mt10">
				<view class="f600 f18 mb10">
					其他（{{other_img.length}}）
				</view>
				<view class="img_box df" v-if="page_width">
					<view class="img_sty" v-for="(item,index) in other_img" :key="index"
						:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="previewImg('other_img',index)">
						<image style="width:100%;height: 100%;" :src="getImgSrc(item)" mode="aspectFill" />

						<view class="detail_btn" @click.stop="deleteImg('other_img',index)">
							<image style="width: 60rpx;"
								:src="getImgSrc('/uploads/20241024/17297417766719c3d068382.png')" mode="widthFix">
							</image>
						</view>
					</view>
					<view class="add_product_item df ac"
						:style="'width:' + comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
						@click="uploadFile('other_img')">
						<van-icon name="plus" size="30" color="#CDCDCD" />
						<view class="name f18 f500 mt10">
							上传照片
						</view>
					</view>

				</view>
			</view>
			<view class="shebei mt10">
				<view class="f600 f18 mb10">
					文件（{{fileList.length}}）
				</view>
				<view class="df ac" style="flex-wrap: wrap;"
					:style="{'padding-bottom': fileList.length == 0 ? '20rpx' : '0'}">
					<image class="w166" src="https://wx.xtwaixie.com/img/upfile1.png" mode="widthFix" @tap="upFile"></image>
				</view>
				<view class="" v-if="fileList && fileList.length != 0">
					<view class="h44 mt8 bgcf7 df ac pd015" v-if="fileList.length != 0" v-for="(it, index) in fileList"
						:key="index">
						<image class="img16" src="https://wx.xtwaixie.com/img/file.png"></image>
						<p class="ml8 f14 c28 f1">{{ it.name }}</p>
						<image class="img16" src="https://wx.xtwaixie.com/img/del3.png" @tap="deleteImg('fileList',index)">
						</image>
					</view>
				</view>
				<view style="height: 30rpx;"></view>
			</view>
		</view>
		<view class="pd15 mt15" hover-class="none" :hover-stop-propagation="false">
			<button class="sub" @tap="onSub"> 完成 </button>
		</view>
		
		<!-- 预览 -->
		<view class="preview_box" v-if="is_preview" @click="is_preview = false">
			<view class="preview_item">
				<view class="swiperBox" v-if="preview_list.length!=0">
					<uni-swiper-dot class="uni-swiper-dot-box" @clickItem=clickItem :info="list"
						:current="current_index" field="content">
						<swiper class="swiper-box" :autoplay="false" @change="change" :current="current_index" 
						:style="[{height: swiperHeight+ 'px',position:'relative',transform:'height 0.7s'}]"
						>
							<swiper-item v-for="(item, index) in preview_list" :key="index">
								<view class="swiper-item" :class="'swiper-item' + index" style="height:auto">
									<image style="width: 100%;" :src="getImgSrc(item)" mode="widthFix"></image>
								</view>
							</swiper-item>
						</swiper>
					</uni-swiper-dot>
				</view>
			</view>
			<view class="df ac sb mt50 pd15" style="padding:0rpx 10rpx 0rpx 40rpx;position: relative;">
				<view>
					<image style="width:26rpx;"
						src="https://wx.xtwaixie.com/img/back2.png" mode="widthFix">
					</image>
				</view>
				<view class="cf f18 suoy">
					{{ current_index + 1 + '/' + preview_list.length }}
				</view>
				<view @click.stop="deletePreImg">
					<image style="width:120rpx;"
						:src="getImgSrc('/uploads/20241024/17297417766719c3d068382.png')" mode="widthFix">
					</image>
				</view>
			</view>
		</view>
	
		<toast :value='showToast' title='微信禁止电脑端小程序上传文件' :ifHtml='true'
			content='1、可将文件发送至“文件传输助手”微信，通过手机上传文件发布。<br/>2、不上传文件发布。后添加微信xtwaixie，平台补充上传图纸文件。' btnText='知道了'
			@change='showToast=false' />
	</view>
</template>

<script>
	
	const http = require('../../utils/http');
	import {
		toast
	} from "@/component/toast.vue"
	import { mapState,mapActions } from 'vuex';  
	export default {
		components: {
			toast
		},
		data() {
			return {
				page_width: 0,
				equipment_img: [],
				company_environment: [],
				other_img: [],
				is_preview: false,
				preview_list: [],
				current_index: 0,
				data_info: null,
				swiperHeight:0,
				flag_arr:'',
				showToast:false,
				fileList:[]
			};
		},
		onReady() { 
			this.getSystemInfo()
		},
		computed: {
			...mapState('file', ['album','file']),
			
			total() {
				const total = this.equipment_img.length + this.company_environment.length + this.other_img.length
				return total
			}
		},
		onLoad(opt) {
			console.log(mapState('file', ['album','file']))
			if (this.album && this.album.length != 0) {
				const categoryMap = {
					'设备展示': this.equipment_img,
					'车间展示': this.company_environment,
					'其他': this.other_img,
				};
				this.album.forEach(item => {
					const category = categoryMap[item.name];
					if (category) {
						category.push(item.url);
					}
				});
			}
			// console.log(this.file)
			// console.log(this.fileList)
			this.fileList = this.file || []
			// console.log(this.album,'album')
			
			// if (this.album && this.album.length != 0) {
			// 	const categoryMap = {
			// 		'设备展示': this.equipment_img,
			// 		'车间展示': this.company_environment,
			// 		'其他': this.other_img,
			// 	};
				
			// 	this.album.forEach(item => {
			// 		console.log(categoryMap,'item')
					
			// 		// const category = categoryMap[item.name];
				
			// 		// category   []
			// 		if (item.name in categoryMap) {
			// 			categoryMap[item.name].push(item.url);
			// 			console.log(categoryMap,'categoryMap')
			// 		}
					
			// 	});
			// }
			// this.fileList = this.file || []
		},
		methods: {
			...mapActions('file', ['updateAlbum','updateFile']),
			
			deletePreImg(){
				const index = this.current_index;
				const data = {
					'equipment_img':this.equipment_img,
					'company_environment':this.company_environment,
					'other_img':this.other_img
				}
				let currentImages = data[this.flag_arr]
				
				this.current_index < currentImages.length - 1 ?  this.current_index++ : this.current_index--
				// this.getCurrentSwiperHeight(`.swiper-item${this.current_index}`);
				if(currentImages.length != 1){
					setTimeout(() => {
					    currentImages.splice(index, 1);
						if(currentImages.length == 1){
							this.current_index = 0
						}
						this.getCurrentSwiperHeight(`.swiper-item${this.current_index}`);
					}, 400);
				} else {
					currentImages.splice(index, 1);
					this.is_preview = false
				}
			},
			deleteImg(type, index) {
				const data = {
					'equipment_img':this.equipment_img,
					'company_environment':this.company_environment,
					'other_img':this.other_img,
					'fileList':this.fileList
				}
				if(data[type]){
					data[type].splice(index,1)
				}
			},
			change(e){
				this.current_index = e.detail.current
				this.getCurrentSwiperHeight(`.swiper-item${this.current_index}`);
			},
			getCurrentSwiperHeight(element) {
				const query = uni.createSelectorQuery().in(this);
				query.select(element).boundingClientRect((data) => {
						// console.log("得到布局位置信息", data);
						this.swiperHeight = data.height
					}).exec();
			},
			previewImg(array, index) {
				const previewMap = {
					'equipment_img':this.equipment_img,
					'company_environment':this.company_environment,
				}
				this.preview_list = previewMap[array] || this.other_img
				this.flag_arr = array
				
				this.current_index = index
				this.is_preview = true
				
				// console.log(this.current_index,`.swiper-item${index}`)
				setTimeout(()=>{
					this.getCurrentSwiperHeight(`.swiper-item${index}`);
				},150)
			},
			async uploadFile(type) {
			    const that = this;
			    const fileTypeMap = {
			        'equipment_img': that.equipment_img,
			        'company_environment': that.company_environment,
			        'other_img': that.other_img
			    };
			    try {
			        const res = await uni.chooseImage();
			        uni.showLoading({ title: '上传中' });
			        const uploadPromises = res[1].tempFiles.map(item => {
			            return http.upLoadFile('base/uploadImg', 'image', item.path, {}).then(rest => {
			                const targetArray = fileTypeMap[type];
			                if (targetArray) {
			                    targetArray.push(rest.data.url);
			                }
			            });
			        });
					console.log(fileTypeMap.equipment_img)
			        await Promise.all(uploadPromises);
			        uni.hideLoading();
			    } catch (err) {
			        uni.hideLoading();
			        that.showToast(err.message || '上传失败');
			    }
			},
			upFile() {
				let that = this;
				let count = 9 - this.fileList.length
				wx.getSystemInfo({
					success: (res) => {
						// res.platform == 'android' || res.platform == 'ios'
						if (res.platform == 'android' || res.platform == 'ios') {
							uni.chooseMessageFile({
								count: count,
								type: 'file',
								success(res) {
									uni.showLoading({
										title: '上传中'
									});
									
									let up_length = 0;
									let list_length = res.tempFiles.length;
									for (let j = 0; j < res.tempFiles.length; j++) {
										let tempFiles = res.tempFiles[j];
										let fileName = tempFiles.name;
										// 获取文件后缀名
										let fileExtension = fileName.split('.').pop().toLowerCase();
										// 如果文件后缀包含unknown,提示用户并跳过该文件
										if(fileExtension.includes('unknown')){
											uni.showToast({
												title:`${fileName} 上传失败`,
												icon:'none',
												duration:2000
											});
											continue;//跳出此文件的上传
										}
										// 执行上传操作
										http.upLoadFile('base/getFile', 'file', tempFiles.path, {})
											.then((res) => {
												up_length = up_length + 1;
												that.fileList.push({
													url: res.data.file,
													name: tempFiles.name
												})
												if (up_length == list_length) {
													uni.hideLoading();
												}
											}).catch((res) => {
												uni.hideLoading();
												uni.showToast({
													title: res.message,
													icon: 'none'
												});
											});
									}
								},
								fail(res) {
									uni.hideLoading();
								}
							});
						} else {
							this.showToast = true
						}
					}
				});
				
			},
			showToast(message) {
				uni.showToast({
					title: message,
					icon: 'none'
				});
			},
			onSub() {
				let list = []
				this.equipment_img.forEach(item=>{
					list.push({
						name:'设备展示',
						url:item
					})
				})
				this.company_environment.map(item=>{
					list.push({
						name:'车间展示',
						url:item
					})
				})
				this.other_img.map(item=>{
					list.push({
						name:'其他',
						url:item
					})
				})
				this.updateAlbum(list)
				this.updateFile(this.fileList)
				uni.navigateBack()
			},
			getSystemInfo() {
				const that = this
				uni.getSystemInfo({
					success: res => {
						that.page_width = res.screenWidth
					}
				})
			},
			comImgWidth(num) {
				const elem = (this.page_width - 100) * 2
				const width = elem / num
				return width
			},
		}
	}
</script>

<style lang="scss">
	// swiper-item{
	// 	top: 50% !important;
	// 	transform: translate(0%,-50%,0) !important;
	// }
	// .swiper-box {
	// 	height: 400rpx;
	// 	min-height: 400rpx;
	// }

	.preview_box {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background-color: #000;
		z-index: 999;

		.preview_item {
			position: absolute;
			top: 50%;
			left: 0;
			width: 100%;
			height: auto;
			transform: translateY(-50%);
		}
	}

	.album_box {
		padding: 30rpx;
	}

	.shebei {}

	.img_sty {
		border-radius: 10rpx;
		overflow: hidden;
		margin-bottom: 10rpx;
		position: relative;

		.detail_btn {
			position: absolute;
			right: 5rpx;
			top: 5rpx;
		}
	}

	.img_box {
		flex-wrap: wrap;

		&>view {
			width: 32%;
			margin-right: 1%;
		}

		&>view:nth-child(3n) {
			margin-right: 0rpx;
		}
	}

	.container2 {

		// display: flex;
		// flex-direction: column-reverse;
		.add_product {
			border-radius: 30rpx;
			padding: 10rpx 10rpx 10rpx 15rpx;
			color: #fff;
			background-color: $xt-primary;

			.add_icon {
				margin-left: 10rpx;
				width: 35rpx;
				height: 35rpx;
				line-height: 30rpx;
				text-align: center;
				border-radius: 50%;
				background-color: #fff;
				color: #1050c7;
			}
		}

		.product_box {
			flex-wrap: wrap;
		}

		.add_product_item {
			margin-bottom: 20rpx;
			width: 48%;
			border: 5rpx solid #CDCDCD;
			justify-content: center;
			flex-direction: column;
			border-radius: 10rpx;
			// padding:10rpx;
			// padding: 50rpx 0rpx;
			box-sizing: border-box;

			.name {
				color: #CDCDCD;
				// padding-bottom: 50rpx;
			}

			.product_img {

				width: 100%;

				image {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}
			}

			.product_tag {
				color: #A2A2A2;

				.product_tag_text {
					width: 100%;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}

			.product_bom {
				border-top: 1px solid #a2a2a2a3;
				padding: 10rpx;
				justify-content: flex-end;
			}
		}
	}
	.suoy{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
	}
</style>